using IdentityManagement.Localization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xms.Abp.Application.Services;

namespace IdentityManagement
{
    [Authorize]
    public class IdentityRoleAppService : XmsCrudAppService<IdentityRole, IdentityRoleResult, Guid, IdentityRolePagedParameter, IdentityRoleCreateParameter, IdentityRoleUpdateParameter>, IIdentityRoleAppService
    {
        protected IIdentityRoleRepository RoleRepository { get; }
        public IdentityRoleAppService(IIdentityRoleRepository repository) : base(repository)
        {
            RoleRepository = repository;
            //ObjectMapperContext = typeof(IdentityManagementApplicationModule);
            LocalizationResource = typeof(IdentityResource);
        }

        protected IdentityRoleManager RoleManager => LazyInject<IdentityRoleManager>();

        public virtual async Task<List<IdentityRoleResult>> GetAllListAsync()
        {
            var list = await Repository.GetListAsync();
            return ObjectMapper.Map<List<IdentityRole>, List<IdentityRoleResult>>(list);
        }

        protected override async Task<IQueryable<IdentityRole>> CreateFilteredQueryAsync(IdentityRolePagedParameter input)
        {
            var query = await base.CreateFilteredQueryAsync(input);
            query = query.WhereIf(!input.Filter.IsNullOrWhiteSpace(), r => r.Name.Contains(input.Filter));
            return query;
        }

        protected override Func<IdentityRoleCreateParameter, IdentityRole> EntityCreator => input => new(GuidGenerator.Create(), input.Name, CurrentTenant.Id)
        {
            IsDefault = input.IsDefault,
            IsPublic = input.IsPublic
        };
        protected override async Task BeforeUpdateAsync(IdentityRole entity, IdentityRoleUpdateParameter input)
        {
            (await RoleManager.SetRoleNameAsync(entity, input.Name)).CheckErrors();
            entity.IsDefault = input.IsDefault;
            entity.IsPublic = input.IsPublic;
        }

        public override async Task DeleteAsync(Guid id)
        {
            await CheckDeletePolicyAsync();
            var role = await RoleManager.GetByIdAsync(id);
            if(role != null)
            {
                await RoleManager.DeleteAsync(role);
            }
        }
    }
}
